Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
¿Reaccionar el componente "agregar" a DOM?

Soy nuevo en React y estoy tratando de representar un componente cuando un usuario intenta iniciar sesión con detalles de inicio de sesión incorrectos. Tengo una página Login.jsx donde presento el formulario de inicio de sesión y manejo toda la lógica de inicio de sesión en una función asíncrona. Todo esto funciona bien. Si los detalles de inicio de sesión son incorrectos, tengo un componente ErrorModal en un div ya establecido con la ID de error-modal.

 ReactDOM.render(<ErrorModal />, document.getElementById('error-modal')) ... function Login() { const userRef = React.useRef() const passRef = React.useRef() const loginErr = React.useRef() const handleLogin = async (e) => { e.preventDefault() requestLogin(userRef.current.value, passRef.current.value, loginErr) } return ( <form className='login-form' onSubmit={handleLogin}> <Field ref={userRef} label='Username:' type='text' /> <Field ref={passRef} label='Password:' type='password' /> <div className='button-wrapper'> <button type='submit' className='btn'>Login</button> </div> <div id='error-modal'></div> </form> ) } export default Login

¿Necesito tener el div modal de error ya en el DOM, o puedo agregar el componente ErrorModal después de otro elemento DOM de alguna manera (como dentro del formulario o simplemente fuera del formulario) y no preocuparme de que el div modal de error sea " codificado"?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Debe utilizar la representación condicional .

Aquí hay un ejemplo:

 function Login() { const [userCredentials, setUserCredentials] = useState({ email: "", password: "" }); const [error, setError] = useState(false); const handleLogin = async (e) => { e.preventDefault(); try { const res = await requestLogin(userCredentials); if (!res.ok) { throw Error("Login failed..."); } } catch (e) { setError(true); console.error(e); } }; const handleUserCredentialsChange = (e) => { setUserCredentials({ ...userCredentials, [e.target.name]: e.target.value }); }; return ( <> <form onSubmit={handleLogin}> <input placeholder="Email" name="email" value={userCredentials.email} onChange={handleUserCredentialsChange} /> <input placeholder="Password" name="password" value={userCredentials.password} type="password" onChange={handleUserCredentialsChange} /> <input type="submit" /> </form> {error && ( <div style={modalContainer}> <div style={{ backgroundColor: "aliceblue", padding: 40 }}> <h1>Something went wrong...</h1> <button onClick={() => setError(false)}>Close</button> </div> </div> )} </> ); } function requestLogin(userCredentials) { return fetch("api/login", { method: "POST", body: JSON.stringify(userCredentials), headers: { "Content-Type": "application/json" } }); } const modalContainer = { position: "absolute", zIndex: 100, top: 0, bottom: 0, left: 0, right: 0, display: "flex", justifyContent: "center", alignItems: "center", backgroundColor: "rgba(0,0,0,0.5)" };

Compruébalo en Code Sandbox si quieres ejecutarlo en el navegador.

about 4 years ago · Juan Pablo Isaza Report

0

puedes hacerlo creando un estado simple como este

 function Login() { const [error,setError]=React.useState("") const userRef = React.useRef() const passRef = React.useRef() const loginErr = React.useRef() const handleLogin = async (e) => { e.preventDefault() const res=requestLogin(userRef.current.value, passRef.current.value, loginErr) //assuming that above function does a post call via fetch //and also assuming that in case of wrong credentials error was passed from backend const data=res.json() if(!res.ok) setError(data.error); } return ( <form className='login-form' onSubmit={handleLogin}> <Field ref={userRef} label='Username:' type='text' /> <Field ref={passRef} label='Password:' type='password' /> <div className='button-wrapper'> <button type='submit' className='btn'>Login</button> </div> <div id='error-modal'>{error.length>0 && error}</div> </form> ) } export default Login
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!